<template>
  <div>
    <!-- 按钮 -->
    <el-button type="primary"  @click="dialogVisible = true">添加新用户</el-button>

    <!-- 表格部分 -->
    <el-table :data="userList"  stripe  border >
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="年龄" prop="age"></el-table-column>
        <el-table-column label="头衔" prop="position"></el-table-column>

        <el-table-column label="创建时间">
          <template v-slot:default="scope">{{ scope.row.addtime | dateFormat }}</template>
        </el-table-column >

        <el-table-column label="操作">
          <template #default="{ row }">
            <div>
            <router-link :to="'/users/' + row.id">详情</router-link>&nbsp;
            <a href="#" @click.prevent="onremove(row.id)">删除---{{ row.id }}</a>
            </div>
          </template>
        </el-table-column>
    </el-table>

    <!-- 对话框部分 -->
    <el-dialog
      title="添加新用户"
      :visible.sync="dialogVisible"
      width="50%" @close="ondialogclose">
      <el-form :model="form" :rules="rules" ref="myaddform">
        <!-- 收集用户名称 -->
        <el-form-item label="用户名称" label-width="80px" prop="name">
          <el-input v-model.trim="form.name" ></el-input>
        </el-form-item>
        <!-- 收集用户年龄 -->
        <el-form-item label="用户年龄" label-width="80px" prop="age">
          <el-input v-model.number="form.age" ></el-input>
        </el-form-item>
        <!-- 收集用户头衔 -->
        <el-form-item label="用户头衔" label-width="80px" prop="position">
          <el-input v-model.trim="form.position" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" >取 消</el-button>
        <el-button type="primary" @click="onaddnewuser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UserList', 
  created() {
    this.getUserList()
  },
  
  data() {
     // 声明验证年龄的函数
   let checkAge = (rule,value,cb)=> {
        if(!Number.isInteger(value)) {
          return cb(new Error('必须为整数！'))
        }
        if(value>100 || value<1) {
          return cb(new Error('必须在 1 到 100 之间！'))
        }
        cb()
      }
    return {
      userList: [],
      dialogVisible: false,
      form: {
        name: '',
        age: '',
        position: ''
      },
      rules: {
          name: [
            { required: true, message: '用户名称是必填项', trigger: 'blur' },
            { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
          ],
          age: [
            { required: true, message: '用户年龄是必填项', trigger: 'blur' },
            { validator: checkAge, trigger: 'blur' }
          ],
          position: [
            { required: true, message: '用户头衔是必填项', trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
          ]
      }
    }
  },
  methods: {
    async getUserList() {
      const { data:res } = await this.$http.get('/api/users') 
      console.log(res)
      if(res.status !== 0) return alert('用户列表获取失败！')
      this.userList = res.data
    },
    ondialogclose() {
      this.$refs.myaddform.resetFields()
    },
    onaddnewuser() {
     this.$refs.myaddform.validate(async valid=> {
       if(!valid) return
      //  添加新用户
      const { data:res } = await this.$http.post('/api/users',  this.form )
      if(res.status !== 0) return this.$message.error('用户添加失败')
      this.$message.success('用户添加成功！')
      this.getUserList()
      this.dialogVisible = false      
      })
    },
    async onremove(id) {
       const confirmresult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirmresult !== 'confirm') return this.$message.info('取消了删除！')

        // this.userList = this.userList.filter(x=>x.id !== id)
        const {data:res } = await this.$http.delete('/api/users/'+ id)
        if(res.status !== 0) return this.$message.error('删除失败！')
        this.$message.success('删除成功！')
        this.getUserList()
    }

  }
}
</script>

<style lang="less" scoped>
  .el-table {
    margin-top: 15px;
  }
</style>